<template>
  <div class="chart-pie-log-root" v-loading="rqLoading" element-loading-text="正在聚合日志信息, 请稍后...">
    <div style="width: 100%;height: 100%;" ref="ChartPieLogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { logPieApi } from "@/api/log";
import { isNull } from "@/assets/utils/obj";
// echarts
import * as echartTheme from '@/assets/styles/xz/echartTheme';
import * as echarts from 'echarts/core';
import { UniversalTransition } from 'echarts/features';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
echarts.use([TitleComponent, TooltipComponent, LegendComponent, PieChart, LabelLayout, GridComponent, LegendComponent, CanvasRenderer, UniversalTransition]);

// -------------------- data
const rqLoading = ref<boolean>(true);
const ChartPieLogRef = ref<any>(null)
let chartPieLog: any;
let chartData: any;

const getLogPie = () => {
  rqLoading.value = true;
  logPieApi({ indexName: 'index_backend_log' }).then(resp => {
    if (isNull(resp.data)) {
      return;
    }
    chartData = resp.data;
    renderChart(
      setTimeout(() => {
        rqLoading.value = false;
      }, 300)
    );
  })
}

const renderChart = (callback?: any) => {
  chartPieLog.setOption(
    {
      title: { top: 5, right: 5, text: '24小时', textStyle: echartTheme.title().textStyle },
      legend: { ...echartTheme.legend(), ...{ orient: 'vertical', itemStyle: { opacity: 1 } } },
      series: [
        {
          type: 'pie',
          right: -110,
          radius: '80%',
          minAngle: 10,
          label: { fontFamily: echartTheme.common().fontFamily, color: echartTheme.common().legendColor },
          itemStyle: {
            color: (param: any) => {
              if (param.data.level.indexOf('DEBUG') > -1) {
                return '#3f8a10';
              }
              if (param.data.level.indexOf('INFO') > -1) {
                return '#c4bbbb';
              }
              if (param.data.level.indexOf('WARN') > -1) {
                return '#ab9336';
              }
              return '#dd4c4c';
            }
          },
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })

  if (callback !== undefined) {
    callback;
  }
}

const reload = () => {
  nextTick(() => {
    getLogPie();
  })
}

onMounted(() => {
  chartPieLog = echarts.init(ChartPieLogRef.value);
  chartPieLog.resize();
})

defineExpose({
  reload
})

</script>

<style scoped lang="scss">
.chart-pie-log-root {
  @include box(100%, 100%);
}
</style>